<template>
    <a-modal
        title="阿里云密钥计算"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
    >
        <a-form-model :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-form-model-item label="地域(Region)">
                <a-select 
                    v-model="form.region" 
                    style="width: 100%;"
                    placeholder="请选择地域"
                    @select="handleRegionChange"
                >
                    <a-select-option 
                        v-for="item in aliCloudTypeOptions" 
                        :key="item"
                        :value="item"
                        :label="item"
                    >
                        {{ item }}
                    </a-select-option>
                </a-select>
            </a-form-model-item>
            <a-form-model-item label="连接域名">
                <a-input v-model="form.domain" />
            </a-form-model-item>
            <a-form-model-item label="DeviceName">
                <a-input v-model="form.deviceName" />
            </a-form-model-item>
            <a-form-model-item label="ProductKey">
                <a-input v-model="form.productKey" />
            </a-form-model-item>
            <a-form-model-item label="DeviceSecret">
                <a-input v-model="form.deviceSecret" />
            </a-form-model-item>
            <a-form-model-item label="TimeStamp">
                <a-input v-model="form.timeStamp" />
            </a-form-model-item>
            <a-form-model-item label="连接密钥">
                <a-input v-model="form.connectionKey" readonly placeholder="点击生成密钥按钮计算" />
            </a-form-model-item>
        </a-form-model>
        
        <!-- 自定义底部按钮 -->
        <template slot="footer">
            <a-button @click="handleCancel">取消</a-button>
            <a-button type="primary" :loading="generatingKey" style="margin-left: 8px;" @click="generateConnectionKey">
                {{ generatingKey ? '计算中...' : '生成密钥' }}
            </a-button>
            <a-button type="primary" :loading="confirmLoading" style="margin-left: 8px;" @click="handleOk">
                确定
            </a-button>
        </template>
    </a-modal>
</template>

<script>
import CryptoJS from 'crypto-js'

export default {
    name: 'AliKeyDialog',
    props: {
        visible: {
            type: Boolean,
            required: true
        },
        aliCloudTypeOptions: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            confirmLoading: false,
            form: {
                region: '',
                domain: '',
                deviceName: '',
                productKey: '',
                deviceSecret: '',
                timeStamp: '',
                connectionKey: ''
            },
            generatingKey: false
        }
    },
    watch: {
        aliCloudTypeOptions: {
            handler(newVal) {
                console.log('🔄 [AliKeyDialog] 阿里云类型选项变化:', newVal)
                if (newVal && newVal.length > 0) {
                    this.form.region = newVal[0]
                }
                this.handleProductKeyChange()
            },
            immediate: true
        },
        'form.productKey': {
            handler() {
                this.handleProductKeyChange()
            }
        }
    },
    methods: {
        // HMAC-SHA1 计算函数
        hmacSha1(key, message) {
            try {
                const hmac = CryptoJS.HmacSHA1(message, key)
                return hmac.toString(CryptoJS.enc.Hex)
            } catch (error) {
                console.error('HMAC-SHA1 计算失败:', error)
                return this.simpleHash(key + message)
            }
        },
        
        // 简单的哈希函数（作为备用）
        simpleHash(str) {
            let hash = 0
            for (let i = 0; i < str.length; i++) {
                const char = str.charCodeAt(i)
                hash = ((hash << 5) - hash) + char
                hash = hash & hash // Convert to 32bit integer
            }
            return Math.abs(hash).toString(16).padStart(8, '0')
        },
        
        // 计算连接密码
        calculatePassword() {
            const { deviceName, productKey, deviceSecret, timeStamp } = this.form
            
            if (!deviceSecret || !deviceName || !productKey || !timeStamp) {
                console.warn('缺少必要的参数来计算密码')
                return ''
            }
            
            // 构建签名字符串
            const mqttUserName = deviceName + '&' + productKey
            const signString = 'clientId' + mqttUserName + 'deviceName' + deviceName + 'productKey' + productKey + 'timestamp' + timeStamp
            
            console.log('🔄 [AliKeyDialog] 签名字符串:', signString)
            
            // 计算 HMAC-SHA1
            const hmacResult = this.hmacSha1(deviceSecret, signString)
            console.log('🔄 [AliKeyDialog] HMAC-SHA1 结果:', hmacResult)
            
            // 转换为大写并返回
            return hmacResult.toUpperCase()
        },
        
        handleOk() {
            // 计算客户端ID和用户名
            const secureMode = '3'
            const signMethod = 'hmacsha1'
            const timeStamp = this.form.timeStamp
            const mqttUserName = this.form.deviceName + '&' + this.form.productKey
            const mqttClientId = mqttUserName + '|securemode=' + secureMode + ',signmethod=' + signMethod + ',timestamp=' + timeStamp + '|'
            
            // 计算连接密码
            const mqttPassword = this.calculatePassword()
            
            // 构建确认信息
            const confirmMessage = `是否要替换 MqttConfig 中的以下信息？
            
服务器地址: ${this.form.domain}
客户端ID: ${mqttClientId}
用户名: ${mqttUserName}
连接密码: ${mqttPassword}`
            
            this.$confirm({
                title: '确认替换',
                content: confirmMessage,
                onOk: () => {
                    this.confirmLoading = true
                    setTimeout(() => {
                        this.confirmLoading = false
                        // 传递计算后的数据给父组件
                        const resultData = {
                            ...this.form,
                            mqttUserName,
                            mqttClientId,
                            mqttPassword
                        }
                        this.$emit('ok', resultData)
                    }, 1000)
                },
                onCancel: () => {
                    // 用户取消，不做任何操作
                }
            })
        },
        handleCancel() {
            this.$emit('cancel')
        },
        handleRegionChange(value) {
            console.log('🔄 [AliKeyDialog] 地域选择变化:', value)
            if (value) {
                const start = value.indexOf('[')
                const end = value.lastIndexOf(']')
                console.log('🔄 [AliKeyDialog] 解析地域:', start, end)
                
                if (start !== -1 && end !== -1) {
                    const regionCode = value.substring(start + 1, end)
                    console.log('🔄 [AliKeyDialog] 提取的区域代码:', regionCode)
                    this.updateDomain(regionCode)
                }
            }
        },
        updateDomain(regionCode) {
            if (regionCode) {
                this.form.domain = `${this.form.productKey || ''}.iot-as-mqtt.${regionCode}.aliyuncs.com`
                console.log('🔄 [AliKeyDialog] 更新后的域名:', this.form.domain)
            }
        },
        // 处理ProductKey变化
        handleProductKeyChange() {
            const region = this.form.region
            if (region) {
                const start = region.indexOf('[')
                const end = region.lastIndexOf(']')
                if (start !== -1 && end !== -1) {
                    const regionCode = region.substring(start + 1, end)
                    this.updateDomain(regionCode)
                }
            }
        },
        async generateConnectionKey() {
            // 验证必要字段
            const requiredFields = ['deviceName', 'productKey', 'deviceSecret', 'timeStamp']
            const missingFields = requiredFields.filter(field => !this.form[field])
            
            if (missingFields.length > 0) {
                this.$message.warning(`请先填写以下字段: ${missingFields.join(', ')}`)
                return
            }
            
            this.generatingKey = true
            try {
                const mqttPassword = this.calculatePassword()
                this.form.connectionKey = mqttPassword
                console.log('🔄 [AliKeyDialog] 生成密钥成功:', mqttPassword)
                this.$message.success('密钥生成成功')
            } catch (error) {
                console.error('生成密钥失败:', error)
                this.$message.error('生成密钥失败')
            } finally {
                this.generatingKey = false
            }
        }
    }
}
</script>

<style scoped>
.ant-form-item {
    margin-bottom: 12px;
}
</style> 